<template>
  <div class="app-container small-margin">
    <SearchForm
      v-show="showSearch"
      v-model="queryParams"
      :options="options.formOps"
      @onQuery="getList"
    >
    </SearchForm>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:user:remove']"
          >删除</el-button
        >
      </el-col> -->

      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <Table
      ref="table"
      :auto-featch="true"
      :fetch-data="fetchData"
      :options="options.table"
      :rowClassName="rowClassName"
    >
      <template #jobType="{ row }">
        {{ zypTypes[row.jobType] }}
      </template>
      <template #actionButton="{ row }">
        <el-button
          type="primary"
          :disabled="!row.content"
          @click="handleEdit(row, zypTypes[row.jobType])"
          >查看</el-button
        >
        <el-button
          type="primary"
          @click="handleExport(row, zypTypes[row.jobType])"
          >导出pdf</el-button
        >
        <!-- <el-button type="primary" @click="getPdf(zypTypes[row.jobType])"
          >导出pdf</el-button
        > -->
      </template>
    </Table>
    <div id="zyps" ref="zypdm">
      <DialogVform
        :formJson="def"
        ref="dialogVform"
        @onSubmit="onSubmit"
        title="作业票详情"
        :slots="[
          ...slots,
          'ztfx',
          'qtjc',
          'aqcsinput2',
          'aqcsinput1',
          'sxkjinput',
          'sxkjqtfx',
          'sytqz',
        ]"
        width="1100px"
        :showButton="false"
      >
        <template #sytqz>
          <div style="text-align: right; margin-right: 30px">
            签字：
            <img class="slotImg" :src="formatSrc(formData.sytqz)" alt="" />
            <span>{{ formatDate(formData.sytqzDt) }}</span>
          </div>
        </template>
        <template v-for="item in slots" #[item]>
          <template v-if="item == 'jsjdr1'">
            <img
              class="slotImg"
              v-for="item in jsjdrList"
              :src="formatSrc(item)"
              alt=""
            />
          </template>
          <template v-else-if="jobType == 4 && item == 'yjqm3'">
            <img
              class="slotImg"
              v-for="item in yjqm3List"
              :src="formatSrc(item)"
              alt=""
            />
          </template>
          <img
            v-else
            class="slotImg"
            :src="
              item.includes('qianming') || item.includes('otherqm')
                ? formatSrc(formData.qianming1)
                : formatSrc(formData[item])
            "
            alt=""
          />
        </template>
        <template #aqcsinput2>
          <div style="text-align: left">
            现场配备灭火器(
            {{ formData.mhqnum }}

            )台，灭火毯(
            {{ formData.mhtnum }}

            )块，消防蒸汽带或消防水带(
            {{ formData.fsdnum }}

            )（监护人）
          </div>
        </template>
        <template #aqcsinput1>
          <div style="text-align: left">
            与动火设备相连接的所有管线已断开，加盲板(
            {{ formData.mbnum }}
            )块，未采取水封或仅关闭阀门的方式代替盲板（监护人）
          </div>
        </template>
        <template #sxkjinput>
          <div style="text-align: left">
            已配备作业应急措施：消防器材（
            {{ formData.xfqcnum }}
            ）、救生绳（
            {{ formData.jssnum }}
            ）、气防装备（
            {{ formData.qfsbnum }}

            ），盛有腐蚀性介质的容器作业现场已配备应急用冲洗水（监护人）
          </div>
        </template>
        <template #ztfx>
          <el-table
            :row-style="{ height: '0' }"
            :cell-style="{ padding: '0' }"
            :header-row-style="{ height: '0' }"
            :data="formData.qitiData"
            border
            style="width: 100%"
          >
            <el-table-column prop="fxsj" label="动火分析时间">
              <template #default="{ row }">
                {{ formatDate(row.fxsj) }}
              </template>
            </el-table-column>
            <el-table-column prop="dbxqt" label="代表性气体"> </el-table-column>
            <el-table-column prop="fxjg" label="分析结果%"> </el-table-column>
            <el-table-column prop="fxr" label="分析人">
              <template #default="{ row }">
                <img class="slotImg" :src="formatSrc(row.fxr)" alt="" />
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template #qtjc>
          <el-table
            :row-style="{ height: '0' }"
            :cell-style="{ padding: '0' }"
            :header-row-style="{ height: '0' }"
            :data="formData.qitiData"
            border
            style="width: 100%"
          >
            <el-table-column prop="fxsj" label="分析时间" width="200">
              <template #default="{ row }">
                {{ formatDate(row.fxsj) }}
              </template>
            </el-table-column>
            <el-table-column prop="dbxqt" label="分析点" width="180">
            </el-table-column>
            <el-table-column prop="fxjg" label="可燃气体检测结果">
            </el-table-column>
            <el-table-column prop="fxr" label="分析人">
              <template #default="{ row }">
                <img class="slotImg" :src="formatSrc(row.fxr)" alt="" />
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template #sxkjqtfx>
          <el-table
            :row-style="{ height: '0' }"
            :cell-style="{ padding: '0' }"
            :header-row-style="{ height: '0' }"
            :data="formData.qitiData"
            border
            style="width: 100%"
          >
            <el-table-column prop="fxsj" label="分析项目">
              <el-table-column label="分析标准"> </el-table-column>
            </el-table-column>
            <el-table-column prop="fxsj" label="有毒有害介质">
              <el-table-column prop="ydyhwz" :label="formData.ydyhwzfxbz">
              </el-table-column>
            </el-table-column>
            <el-table-column prop="" label="可燃气">
              <el-table-column prop="krqt" :label="formData.krqtfxbz">
              </el-table-column>
            </el-table-column>

            <el-table-column prop="dbxqt" label="含氧量">
              <el-table-column prop="hyl" label="19.5%-21%"> </el-table-column>
            </el-table-column>
            <el-table-column prop="fxsj" label="取样时间" width="220">
              <template #default="{ row }">
                {{ formatDate(row.fxsj) }}
              </template>
            </el-table-column>

            <el-table-column prop="fxbw" label="分析部位"> </el-table-column>
            <el-table-column prop="fxr" label="分析人">
              <template #default="{ row }">
                <img class="slotImg" :src="formatSrc(row.fxr)" alt="" />
              </template>
            </el-table-column>
          </el-table>
        </template>
      </DialogVform>
    </div>
  </div>
</template>

<script setup>
import Table from "@/components/Table/index.vue";
import SearchForm from "@/components/searchForm/index";
import DialogVform from "@/components/dialogVform/zyp.vue";
import { apis as APIS } from "@/api/zygl/zyp.js";
import formJson from "./piaoju.json";
import { useAsyncData, useFormJsonNew } from "@/views/hooks/useAsyncData.js";
import def from "../../zygl/zyxkzbl/consts/default.json";
import { slotsOptions } from "../../zygl/zyxkzbl/consts/slots";
import jsons from "../../zygl/zyxkzbl/consts/json";
// import { parseTime } from "@/utils/ruoyi.js";

const { proxy } = getCurrentInstance();
const zypTypes = {
  1: "吊装安全作业票",
  2: "动火安全作业票",
  3: "高处安全作业票",
  4: "动土安全作业票",
  5: "临时用电安全作业票",
  6: "动用射线安全作业票",
  7: "断路安全作业票",
  8: "盲板抽堵安全作业票",
  9: "设备开孔安全作业票",
  10: "受限空间安全作业票",
};
const formatDate = (time) => {
  if (time) {
    const date = new Date(time);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const h = date.getHours();
    const m = date.getMinutes();
    return `${year}年${padZero(month)}月${padZero(day)}日 ${padZero(
      h
    )}时${padZero(m)}分`;
  } else {
    return null;
  }
};

//补零函数
function padZero(n) {
  return n < 10 ? "0" + n : n;
}

const formatDateValue = (time) => {
  if (time) {
    let str = "";
    try {
      const date = new Date(time);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const h = date.getHours();
      const m = date.getMinutes();
      str = `${year}-${padZero(month)}-${padZero(day)} ${padZero(h)}:${padZero(
        m
      )}`;
    } catch (error) {
      str = null;
    }
    return str;
  } else {
    return null;
  }
};
const ops = useFormJsonNew(formJson, {
  sort: [],
  sortable: [],
});
const options = reactive({
  table: ops,
  formOps: ops.filter((i) =>
    ["jobType", "specialNumber", "local", "jobStartDate", "cardType"].includes(
      i.prop
    )
  ),
});
const showSearch = ref(true);

const dialogVform = ref();
const slots = ref(slotsOptions[1]);
const table = ref();
const filterForm = ref({});
const formData = ref({});
const jsjdrList = ref([]);
const yjqm3List = ref([]);
const jobType = ref("");
const handleEdit = (row, name) => {
  jobType.value = row.jobType;
  const json = jsons[row.jobType];
  slots.value = slotsOptions[row.jobType];
  // formData.value = JSON.parse(row.content);
  const data = JSON.parse(row.content);

  let newData = {};
  Object.keys(data).forEach((item) => {
    if (item.includes("Dt")) {
      newData[item] = formatDateValue(data[item]);
    } else if (data[item] && data[item].length) {
      newData[item] = data[item];
    } else {
      newData[item] = "无";
    }
  });
  formData.value = newData;
  let jsjdr = [];
  if (formData.value.jsjdr && formData.value.jsjdr instanceof Array) {
    jsjdr = [...formData.value.jsjdr];
  }
  if (formData.value.jsjdr1 && !jsjdr.includes(formData.value.jsjdr1)) {
    jsjdr.push(formData.value.jsjdr1);
  }
  let yjqm3 = [];
  if (jobType.value == 4) {
    if (formData.value.yjqm3 && formData.value.yjqm3 instanceof Array) {
      yjqm3 = [...formData.value.yjqm3];
    }
    if (formData.value.yjqm3 && !jsjdr.includes(formData.value.yjqm3)) {
      yjqm3.push(formData.value.yjqm3);
    }
    yjqm3List.value = yjqm3 || [];
  }
  jsjdrList.value = jsjdr || [];
  dialogVform.value.open(
    {
      ...newData,
      titleCode: row.specialNumber,
      glqtzyp: row.changeBillNumber || "无",
      name,
    },
    json || {}
  );
};
const formatList = (list) => {
  return list.map((item) => {
    return {
      ...item,
      newContent: JSON.parse(row.content),
    };
  });
};
const { onSubmit, fetchData, getList, queryParams, dialogType } = useAsyncData({
  APIS,
  formJson,
  dialogVform,
  table,
  proxy,
  filterForm: filterForm.value,
});
const handleExport = (row) => {
  APIS.exportPdf(row.id, row.specialNumber + zypTypes[row.jobType]);
};
// const changeParent = (p) => {
//   filterForm.value.ptw = p.billNumber || null;
//   getList();
// };
// defineExpose({
//   changeParent,
// });

const formatSrc = (url) => {
  if (url) {
    return `/dev-api/file/download?url=${url}`;
  }
};

const wgqz = {
  1: "yjqm5",
  2: "yjqm7",
  3: "yjqm5",
  4: "yjqm5",
  5: "yjqm5",
  6: "yjqm4",
  7: "yjqm4",
  8: "yjqm4",
  9: "yjqm4",
  10: "yjqm5",
};

const rowClassName = ({ row, rowIndex }) => {
  const data = JSON.parse(row.content);
  if (!data) {
    return "deepred";
  }
  const nowTime = Date.now();
  let jobDate = data.jobDate;
  let endTime = null;
  if (jobDate && jobDate.length == 2) {
    endTime = new Date(jobDate[1]).getTime();
  }
  console.log(data.jobDate, rowIndex);
  if (endTime && nowTime >= endTime && !data[wgqz[row.jobType + ""]]) {
    return "deepred";
  } else if (endTime && nowTime < endTime && !data[wgqz[row.jobType + ""]]) {
    return "yellow";
  } else if (!!data[wgqz[row.jobType + ""]]) {
    return "";
  }
};
</script>

<style lang="scss">
.slotImg {
  // width: 100%;
  max-width: 150px;
  max-height: 30px;
}
.dialogVform {
  .el-radio.el-radio--small {
    margin-right: 0 !important;
  }
}
</style>
